<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      title="新增考试"
      width="600"
      :before-close="handleClose"
      align-center
    >
      <div class="addExamContainer">
        <el-form
          :model="addExamForm"
          label-width="auto"
          style="max-width: 600px"
          :rules="rules"
          ref="addExamFormRef"
        >
          <el-form-item
            label="名称："
            prop="examName"
          >
            <el-input
              v-model="addExamForm.examName"
              placeholder="请输入考试名称"
              :maxlength="60"
            />
          </el-form-item>

          <el-form-item
            label="班级："
            prop="deptids"
          >
            <el-select
              multiple
              v-model="addExamForm.deptids"
            >
              <el-option
                v-for="item in deptList"
                :key="item.id"
                :label="item.deptName"
                :value="item.deptId"
              >

              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="试卷："
            prop="examPaperId"
          >
            <el-select
              placeholder="请选择考试试卷"
              v-model="addExamForm.examPaperId"
            >
              <el-option
                v-for="item in paperList"
                :key="item.paperId"
                :value="item.paperId"
                :label="item.paperTitle"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="时间："
            prop="examStart"
          >
            <el-config-provider :locale="locale">
              <el-date-picker
                style="width: 280px;"
                v-model="time"
                type="datetimerange"
                range-separator="-"
                format="YYYY-MM-DD HH:mm:ss"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                date-format="YYYY-MM-DD"
                time-format="HH:mm"
                :disabled-date="disabledDate"
                @change="handleTimeChange"
              />
            </el-config-provider>
          </el-form-item>

          <el-form-item
            label="时长："
            prop="examTime"
          >
            <el-input
              v-model="addExamForm.examTime"
              :maxlength="999"
              placeholder="请输入考试时长"
            ></el-input>
          </el-form-item>

          <el-form-item label="备注：">
            <el-input
              type="textarea"
              :span="3"
              :maxlength="200"
              v-model="addExamForm.remark"
            ></el-input>
          </el-form-item>

        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            @click="handleClose"
            class="cancelBtn"
            plain
          >取消</el-button>
          <el-button
            type="primary"
            @click="confirmAddTest"
            class="saveBtn"
            plain
          >
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, defineEmits } from 'vue';
// 引入查询部门列表的接口
import { listDept } from '@/api/system/dept.js'

// 引入查询试卷列表的接口
import { testPaperList } from '@/api/assessment/testpapermanage.js'

// 引入新增考试，修改考试的接口
import { addExam, updateExam } from '@/api/assessment/exammanage.js'

import { ElMessage } from 'element-plus';

import zhCn from "element-plus/es/locale/lang/zh-cn";

const locale = zhCn;

import moment from 'moment';

const emit = defineEmits(['updateTable'])

const dialogVisible = ref(false)

const deptList = ref([])
// 查询部门列表
async function getDeptList () {
  const res = await listDept()
  // console.log(res)
  deptList.value = res.rows
}
getDeptList()

const paperList = ref([])
// 查询试卷列表
async function getTestPaperList () {
  const res = await testPaperList({
    pageNum: 1,
    pageSize: 100
  })
  // console.log(res)
  paperList.value = res.data.records
}
getTestPaperList()

const addExamForm = ref({
  examName: '',
  deptids: [],
  examPaperId: null,
  examStart: '',
  examEnd: '',
  examTime: null
})

const time = ref([])
// 格式化时间
function handleTimeChange (time) {
  // console.log(time)
  addExamForm.value.examStart = moment(time[0]).format('YYYY-MM-DD HH:mm')
  addExamForm.value.examEnd = moment(time[1]).format('YYYY-MM-DD HH:mm')
  // console.log(addExamForm.value.examStart, addExamForm.value.examEnd)
}

const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

const rules = ref({
  examName: [
    { required: true, message: '请输入考试名称', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value.trim() === '') {
          callback(new Error('请输入非空值且不能包含空格'));
        } else if (/\s/.test(value)) {
          // 使用正则表达式检查是否有空格  
          callback(new Error('输入不能包含空格'));
        } else {
          callback();
        }
      }, trigger: "blur"
    }

  ],
  deptids: [
    { required: true, message: '请选择班级', trigger: 'change' },
  ],
  examPaperId: [
    { required: true, message: '请选择试卷', trigger: 'change' },
  ],
  examStart: [
    { required: true, message: '请选择考试时间', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        const startTime = moment(value)
        const endTime = moment(addExamForm.value.examEnd)
        const intervalTime = endTime.diff(startTime, 'minutes')
        if (startTime == endTime) {
          callback(new Error('考试时长不能等于0'))
        }
        callback()
      },
      trigger: 'blur'
    },

  ],

  examTime: [
    { required: true, message: '请输入考试时长', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        const startTime = moment(addExamForm.value.examStart)
        const endTime = moment(addExamForm.value.examEnd)
        const intervalTime = endTime.diff(startTime, 'minutes')
        if (intervalTime < value) {
          callback(new Error('考试时长不能大于考试时间'))
        } else if (value < 0) {
          callback(new Error('考试时长不能小于0'))
        } else if (value > 999) {
          callback(new Error('考试时长不能大于三位数'))
        }
        callback()
      },
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value.trim() === '') {
          callback(new Error('请输入非空值且不能包含空格'));
        } else if (/\s/.test(value)) {
          // 使用正则表达式检查是否有空格  
          callback(new Error('输入不能包含空格'));
        } else {
          callback();
        }
      }, trigger: "blur"
    }
  ],

})

const addExamFormRef = ref(null)

// 确定新增考试
async function confirmAddTest () {
  const intervalTime = moment(addExamForm.value.examEnd).diff(moment(addExamForm.value.examStart), 'minutes')
  addExamFormRef.value.validate(async (valid) => {
    if (intervalTime > addExamForm.examTime) {
      return ElMessage({
        type: 'warning',
        message: '考试结束时间不能大于考试时长'
      })
    }

    if (intervalTime < 0) {
      return ElMessage({
        type: 'warning',
        message: '考试结束时间不能小于考试开始时间'
      })
    }
    if (valid) {
      if (addExamForm.value.examId) {
        await updateExam({
          ...addExamForm.value
        })
        ElMessage({
          type: 'success',
          message: '修改考试成功'
        })
      } else {
        await addExam({
          ...addExamForm.value
        })
        ElMessage({
          type: 'success',
          message: '新增考试成功'
        })
      }
      emit('updateTable')

      // console.log(res)
      handleClose()
    }
  })
}
// 处理关闭的方法
function handleClose () {
  addExamForm.value = {
    examName: '',
    deptids: [],
    examPaperId: null,
    examStart: '',
    examEnd: ''
  }
  time.value = []
  dialogVisible.value = false
  addExamFormRef.value.resetFields()
}

defineExpose({
  dialogVisible,
  addExamForm,
  time
})

</script>

<style lang='scss' scoped>
.addExamContainer {
  padding: 0 112px;
  ::v-deep(.el-form-item__label) {
    font-size: 16px;
    color: #696969;
    font-weight: 400;
  }

  ::v-deep(.el-select.el-select--default) {
    width: 320px;
  }
}

.cancelBtn {
  width: 108px;
  height: 40px;
  border-radius: 6px 6px 6px 6px;
  border: 1px solid #5974ff;
  font-size: 16px;
  color: #5974ff;
}

.saveBtn {
  width: 108px;
  height: 40px;
  background: #5974ff;
  border-radius: 6px 6px 6px 6px;
  font-size: 16px;
  color: #ffffff;
}
// 模态框居中显示
::v-deep(.el-dialog:not(.is-fullscreen)) {
  margin: auto !important;
}
</style>
